using System;
using System.Reactive.Subjects;
using JetBrains.Annotations;
using Rsdn.SmartApp;

namespace Rsdn.Janus
{
    [Service(typeof(IForumsAggregatesService))]
    internal sealed class ForumsAggregatesService : IForumsAggregatesService, IDisposable
    {
        private readonly Subject<EventArgs> _aggregatesChanged = new Subject<EventArgs>();
        private readonly IDisposable _eventsSubscription;

        private int messagesCount;
        private int unreadMessagesCount;
        private int unreadRepliesToMeCount;

        public ForumsAggregatesService([NotNull] IServiceProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            UpdateAggregates();

            _eventsSubscription = EventBrokerHelper.SubscribeEventHandlers(this, provider);
        }

        #region Implementation of IForumsAggregatesService


        public int MessagesCount
        {
            get { return messagesCount; }
            private set { messagesCount = value; }
        }

        public int UnreadMessagesCount
        {
            get { return unreadMessagesCount; }
            private set { unreadMessagesCount = value; }
        }

        public int UnreadRepliesToMeCount
        {
            get { return unreadRepliesToMeCount; }
            private set { unreadRepliesToMeCount = value; }
        }

        public IObservable<EventArgs> AggregatesChanged
        {
            get { return _aggregatesChanged; }
        }

        #endregion

        #region Implementation of IDisposable

        public void Dispose()
        {
            _eventsSubscription.Dispose();
        }

        #endregion

        #region Private Members

        private void UpdateAggregates()
        {
            MessagesCount = 0;
            UnreadRepliesToMeCount = 0;
            UnreadMessagesCount = 0;

            if (Forums.Instance.ForumList != null)
            {
                foreach (Forum forum in Forums.Instance.ForumList)
                {
                    if (!forum.IsVirtual)
                    {
                        MessagesCount += forum.MessagesCount;
                        UnreadRepliesToMeCount += forum.RepliesToMeUnread;
                        UnreadMessagesCount += forum.Unread;
                    }
                }
            }
        }

        [EventHandler(ForumEventNames.AfterForumEntryChanged)]
        private void AfterForumEntryChanged(ForumEntryChangedEventArgs arg)
        {
            if ((arg.ChangeType & ForumEntryChangeType.ReadMark) == 0)
            {
                return;
            }

            UpdateAggregates();

            _aggregatesChanged.OnNext(EventArgs.Empty);
        }

        #endregion
    }
}